package com.alameda.utils;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * 多线程工具类
 *
 * @author Lv
 * @date 2025/1/6
 */
public class ThreadPoolUtils {
    /**
     * 任务队列容量
     */
    private static final int CAPACITY = 10000;

    /**
     * 线程池核心线程数  (内核*2 + 1)
     */
    public static final int CORE_POOL_SIZE = 17;

    /**
     * 线程池最大线程数
     */
    private static final int MAXIMUM_POOL_SIZE = 30;

    /**
     * 额外线程空状态生存时间
     */
    private static final Long KEEP_ALIVE_TIME = 0L;

    /**
     * 时间单位
     */
    private static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;

    /**
     * 定义线程池
     */
    private static final ExecutorService EXECUTOR_SERVICE;

    /**
     * 静态代码块初始化线程池
     */
    static {
        // 创建阻塞队列
        BlockingQueue<Runnable> workingQueue = new ArrayBlockingQueue<Runnable>(CAPACITY);
        // 创建拒绝执行处理器
        RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
        // 设置线程名称
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("yunzhuan-pool-%d").build();
        // 初始化线程池
        EXECUTOR_SERVICE = new ThreadPoolExecutor(CORE_POOL_SIZE,
                MAXIMUM_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TIME_UNIT,
                workingQueue,
                namedThreadFactory,
                rejectedExecutionHandler);
    }

    /**
     * 开启多线程
     *
     * @param runnable 任务线程
     */
    public static void execute(Runnable runnable) {
        // 执行任务线程
        EXECUTOR_SERVICE.execute(runnable);
    }
}